import TableRender from '@/render/TableRender'
import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import toNative from '@/utils/toNative'
import type { FilterDto } from '@/render/FilterRender'
import { getKeyToEnum, AllowStatusCnEnum } from '@/const/enum'
import { getInsurancePlans, updateCompanyPlans } from '@/api/insurance/period'
import renderModal, {
    getModelValue,
    initModelValue,
    renderForm,
    type FormModalDto
} from '@/components/modal/Modal'
import type { InsurancePlanDto, PlanReqDto } from '@/api/insurance/period/types'
import Dialog from '@/components/dialog/Index'
import { Button, Col, message, Row } from 'ant-design-vue'

@Component
export class DialogEditInsurancePlan extends TableRender {
    @Prop() planInfo!: InsurancePlanDto
    @Prop() show!: boolean

    showDialog = false
    noTablePadding = true

    exceedConfigData = {} as Record<string, any> // 六类价格配置返回给后台用的数据

    otherItems = {
        insureBase: {
            name: '5类占比',
            element: 'input',
            span: 12
        },
        beginTime: {
            name: '生效时间',
            element: 'datetime',
            span: 12,
            params: {
                type: 'datetime',
                valueFormat: 'YYYY-MM-DD'
            }
        },
        hasEnsure: {
            name: '是否首次投保',
            element: 'select',
            span: 12,
            options: [
                { label: '是', value: true },
                { label: '否', value: false }
            ]
        },
        endTime: {
            name: '结束时间',
            element: 'datetime',
            span: 12,
            params: {
                type: 'datetime',
                valueFormat: 'YYYY-MM-DD'
            }
        },
        allowedDetermineStatus: {
            name: '是否允许减保',
            element: 'select',
            span: 12,
            options: getKeyToEnum(AllowStatusCnEnum)
        },
        isCompanyAllowedRepeat: {
            name: '是否允许在别的保司进行投保',
            element: 'select',
            span: 12,
            options: getKeyToEnum(AllowStatusCnEnum)
        },
        isAllowedRepeat: {
            name: '是否允许重复投保',
            element: 'select',
            span: 12,
            options: getKeyToEnum(AllowStatusCnEnum)
        },
        ensureLimit: {
            name: '最低投保人数',
            element: 'input',
            span: 12
        }
    } as FilterDto

    @Emit('update:show')
    updateShow(val: boolean) {
        return val
    }

    @Watch('show', { immediate: true })
    handleWatchShow() {
        this.showDialog = this.show
        if (this.showDialog) {
            this.basicForm = renderForm(this.basicFormConfig)
            this.getDataAndInit()
        }
    }

    @Watch('showDialog', { immediate: true })
    handleWatchShowDialog() {
        this.updateShow(this.showDialog)
    }

    basicFormConfig = this.initBasicFormConfig() as FormModalDto
    initBasicFormConfig() {
        return {
            title: '',
            width: '800px',
            theme: 'light',
            show: false,
            items: {
                price: {
                    name: '3类价格',
                    element: 'input',
                    span: 12
                },
                ensureLimitThree: {
                    name: '3类投保基数限制',
                    element: 'input',
                    span: 12
                },
                priceFour: {
                    name: '4类价格',
                    element: 'input',
                    span: 12
                },
                ensureLimitFour: {
                    name: '4类投保基数限制',
                    element: 'input',
                    span: 12
                },
                priceFive: {
                    name: '5类价格',
                    element: 'input',
                    span: 12
                },
                ensureLimitFive: {
                    name: '5类投保基数限制',
                    element: 'input',
                    span: 12
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                message.success('更新成功')
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    async getDataAndInit() {
        const res = await getInsurancePlans(this.planInfo?.id)
        // 动态生成6类价格
        if (res.exceedConfig) {
            const data = JSON.parse(res.exceedConfig)
            const exceedData = {} as FilterDto
            for (const key in data) {
                const indexName = key.replace(/\D/g, '')
                exceedData[(key as keyof typeof exceedData) + 'price'] = {
                    name: indexName + '类价格',
                    element: 'input',
                    span: 12,
                    defaultValue: data[key][`p${indexName}`]
                }
                exceedData[(key as keyof typeof exceedData) + 'limit'] = {
                    name: indexName + '类投保基数限制',
                    element: 'input',
                    span: 12,
                    defaultValue: data[key][`el${indexName}`]
                }

                this.exceedConfigData[key] = {
                    [`${key}price`]: 0,
                    [`${key}limit`]: 0
                }
            }
            this.basicFormConfig.items = {
                ...this.basicFormConfig.items,
                ...exceedData
            }
        }
        this.basicFormConfig.items = {
            ...this.basicFormConfig.items,
            ...this.otherItems
        }

        initModelValue(this.basicFormConfig, res)
    }

    createExceedConfigString(data: PlanReqDto) {
        if (!Object.keys(this.exceedConfigData)?.length) return null
        const res = {} as Record<string, any>
        for (const key in this.exceedConfigData) {
            const indexName = key.replace(/\D/g, '')
            res[key] = {} as Record<string, any>
            for (const innerKey in this.exceedConfigData[key]) {
                res[key].name = `${indexName}类`
                if (innerKey.includes('price')) {
                    res[key]['p' + indexName] = data[innerKey as keyof typeof data]
                }
                if (innerKey.includes('limit')) {
                    res[key]['el' + indexName] = data[innerKey as keyof typeof data]
                }
            }
        }
        return JSON.stringify(res)
    }

    async onSubmit() {
        const data = getModelValue(this.basicFormConfig) as PlanReqDto
        data.id = this.planInfo?.id
        data.companyName = this.planInfo?.companyName
        data.insurCompanyPlanName = this.planInfo?.insurCompanyPlanName
        data.exceedConfig = this.createExceedConfigString(data)
        await updateCompanyPlans(data)
        this.showDialog = false
        message.success('修改成功')
        this.reloadPage()
    }

    render() {
        return (
            <Dialog v-model={this.showDialog} width={900} title="修改公司保险方案" showClose>
                <Row class="pb-20px border-b border-b-solid">
                    <Col lg={12} sm={24}>
                        <div class="flex text-lg">
                            <div class="text-black-300">公司名称：</div>
                            <div>{this.planInfo.companyName}</div>
                        </div>
                    </Col>
                    <Col lg={12} sm={24}>
                        <div class="flex text-lg">
                            <div class="text-black-300">方案名称：</div>
                            <div>{this.planInfo.insurCompanyPlanName}</div>
                        </div>
                    </Col>
                </Row>
                <div class="mt-20px">{this.basicForm.element()}</div>
                <div class="flex justify-center gap-20px">
                    <Button onClick={() => (this.showDialog = false)}>取消</Button>
                    <Button type="primary" onClick={this.onSubmit}>
                        确定
                    </Button>
                </div>
            </Dialog>
        )
    }
}

export default toNative<{ planInfo: InsurancePlanDto }, {}>(DialogEditInsurancePlan)
